package com.fengwk.support.websocket;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

public class WebSocketUtils {

	private final static Logger logger = LoggerFactory.getLogger(WebSocketUtils.class);
	
	private WebSocketUtils() {}
	
	/**
	 * 发送消息
	 * @param session
	 * @param message
	 */
	public static void sendMessage(WebSocketSession session, WebSocketMessage<?> message) {
		if (isOpen(session)) {
			try {
				session.sendMessage(message);
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
	}
	
	public static boolean sendMessage(WebSocketSession session, String msg) {
		if (isOpen(session)) {
			try {
				WebSocketMessage<String> message = new TextMessage(msg);
				session.sendMessage(message);
				return true;
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
		return false;
	}
	
	/**
	 * 关闭WebSocketSession
	 * @param session
	 */
	public static void closeSession(WebSocketSession session) {
		if(isOpen(session)) {
			try {
				session.close();
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
	}
	
	private static boolean isOpen(WebSocketSession session) {
		return session != null && session.isOpen();
	}
	
}
